package com.zpark.service.impl;

import com.zpark.base.AccountTransactionBase;
import com.zpark.dao.IAccountDao;
import com.zpark.pojo.Account;
import com.zpark.service.IAccountService;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 账户业务层接口实现类
 */
public class AccountServiceImpl extends AccountTransactionBase implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(Integer id1, Integer id2, Double money) {
        // 获取事务
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        // 开启事务
        TransactionStatus transaction = transactionManager.getTransaction(definition);


        try {
            // 查询转出id账户数据
            Account acc1 = accountDao.selectById(id1);
            // 判断金额是否充足
            if (acc1.getMoney() < money) {
                // 转账错误，余额不足
                throw new RuntimeException("余额不足");
            }
            // 查询转入id账户数据
            Account acc2 = accountDao.selectById(id2);
            // 执行转账业务
            // 将id1账户的money转出
            accountDao.updateById(id1, acc1.getMoney() - money);
            // 人为制作错误
            int num = 2/0;
            // 修改id2的money
            accountDao.updateById(id2, acc2.getMoney() + money);

            // 提交事务
            transactionManager.commit(transaction);

        } catch(Exception e) {
            // 回滚事务
            transactionManager.rollback(transaction);
            e.printStackTrace();
        }

    }
}
